// ignore_for_file: use_build_context_synchronously

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:logger/logger.dart';
import '../project_provider.dart';
import 'package:flutter/services.dart';
import 'openvpn_service.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final FocusNode _usernameFocusNode = FocusNode();
  final FocusNode _passwordFocusNode = FocusNode();
  bool _isLoading = false;
  bool _isLoggingIn = false;
  bool _rememberPassword = false;
  bool _autoLogin = false;
  DateTime? lastBackPressTime;
  final OpenVPNService vpnService = OpenVPNService();
  final Logger logger = Logger();
  Completer<void>? _loginCompleter;
  String _vpnStatus = 'DISCONNECTED'; // 跟踪 VPN 状态

  @override
  void initState() {
    super.initState();
    // 尽早触发自动 VPN 连接和凭据加载
    _loadSavedCredentials();
  }

  Future<void> _autoConnectVPN() async {
    logger.i('开始检查自动 VPN 连接');
    final prefs = await SharedPreferences.getInstance();
    final vpnConnectedOnce = prefs.getBool('vpn_connected_once') ?? false;
    final ovpnContent = prefs.getString('ovpn_content');
    final keyContent = prefs.getString('key_content');
    final isManualLogout = prefs.getBool('manual_logout') ?? false;

    logger.i(
      '检查自动 VPN 连接状态: vpn_connected_once=$vpnConnectedOnce, ovpnContent=${ovpnContent != null}, keyContent=${keyContent != null}, isManualLogout=$isManualLogout',
    );

    final completer = Completer<void>();

    // 如果是手动登出，不重新触发 VPN 连接
    if (isManualLogout) {
      logger.i('检测到手动登出，跳过自动 VPN 连接');
      completer.complete();
      return completer.future;
    }

    if (vpnConnectedOnce && ovpnContent != null && keyContent != null) {
      try {
        await vpnService.init(
          onVPNStatusChanged: (status) {
            setState(() {
              _vpnStatus = status; // 更新 VPN 状态
            });
            logger.i('自动 VPN 状态更新: $status');
            if (status == 'CONNECTED') {
              logger.i('VPN 连接成功，完成等待');
              if (!completer.isCompleted) {
                completer.complete();
              }
            }
          },
          onConnectionStatusChanged: (status) {
            logger.i(
              '自动 VPN 连接详情: 持续时间=${status.duration}, 接收=${status.byteIn}, 发送=${status.byteOut}',
            );
          },
        );
        vpnService.connect(ovpnContent, keyContent); // 异步启动连接
        logger.i('自动 VPN 连接已启动');
      } catch (e, stackTrace) {
        logger.e('自动 VPN 连接失败: $e\n堆栈跟踪: $stackTrace');
        if (!completer.isCompleted) {
          completer.complete();
        }
      }
    } else {
      logger.w(
        '自动 VPN 连接未触发: vpn_connected_once=$vpnConnectedOnce, ovpnContent=${ovpnContent != null}, keyContent=${keyContent != null}',
      );
      completer.complete();
    }

    // 设置 0.5 秒超时
    Future.delayed(const Duration(milliseconds: 500), () {
      if (!completer.isCompleted) {
        logger.w('VPN 连接超时，继续执行后续逻辑');
        completer.complete();
      }
    });

    return completer.future;
  }

  Future<void> _loadSavedCredentials() async {
    logger.i('并行加载凭据和触发自动 VPN 连接');
    final prefsFuture = SharedPreferences.getInstance();
    final vpnFuture = _autoConnectVPN(); // 并行触发 VPN 连接

    final prefs = await prefsFuture;
    if (!mounted) {
      logger.w('组件未挂载，取消凭据加载');
      return;
    }

    setState(() {
      _usernameController.text = prefs.getString('username') ?? '';
      _rememberPassword = prefs.getBool('rememberPassword') ?? false;
      _autoLogin = prefs.getBool('autoLogin') ?? false;
      if (_autoLogin || _rememberPassword) {
        _passwordController.text = prefs.getString('password') ?? '';
      }
      logger.i(
        '凭据加载完成: username=${_usernameController.text}, autoLogin=$_autoLogin, hasPassword=${_passwordController.text.isNotEmpty}',
      );
    });

    // 等待 VPN 连接完成（或 0.5 秒超时）
    await vpnFuture;
    logger.i('VPN 连接完成（或超时），检查自动登录条件');

    if (_autoLogin &&
        _usernameController.text.isNotEmpty &&
        _passwordController.text.isNotEmpty) {
      if (mounted && !_isLoggingIn) {
        setState(() {
          _isLoggingIn = true;
          _isLoading = true;
        });
        logger.i('触发自动登录');
        await _login(context);
      } else {
        logger.w('自动登录未触发: mounted=$mounted, isLoggingIn=$_isLoggingIn');
      }
    } else {
      logger.w(
        '自动登录条件不满足: autoLogin=$_autoLogin, username=${_usernameController.text}, hasPassword=${_passwordController.text.isNotEmpty}',
      );
    }
  }

  Future<void> _saveCredentials() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('username', _usernameController.text);
    await prefs.setBool('rememberPassword', _rememberPassword);
    await prefs.setBool('autoLogin', _autoLogin);
    if (_autoLogin || _rememberPassword) {
      await prefs.setString('password', _passwordController.text);
    } else {
      await prefs.remove('password');
    }
    await prefs.setBool('manual_logout', false); // 重置手动登出标志
    logger.i(
      '凭据保存完成: username=${_usernameController.text}, autoLogin=$_autoLogin, rememberPassword=$_rememberPassword',
    );
  }

  void _cancelLogin() {
    if (_isLoggingIn) {
      setState(() {
        _isLoggingIn = false;
        _isLoading = false;
      });
      if (_loginCompleter != null && !_loginCompleter!.isCompleted) {
        _loginCompleter!.complete();
      }
      logger.i('自动登录已取消');
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('登录已取消')));
    }
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _usernameFocusNode.dispose();
    _passwordFocusNode.dispose();
    super.dispose();
  }

  Future<void> _login(BuildContext context) async {
    if (_usernameController.text.isEmpty || _passwordController.text.isEmpty) {
      if (mounted) {
        setState(() {
          _isLoggingIn = false;
          _isLoading = false;
        });
        logger.w('登录失败: 用户名或密码为空');
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('请填写用户名和密码')));
      }
      return;
    }

    setState(() {
      _isLoading = true;
      _isLoggingIn = true;
    });

    _loginCompleter = Completer<void>();
    const String host = '10.8.0.244:27017';
    const String database = 'test';
    final connectionString =
        'mongodb://${_usernameController.text}:${_passwordController.text}@$host/$database?authSource=admin&authMechanism=SCRAM-SHA-256';

    int retryCount = 0;
    const maxRetries = 10; // 最多重试 10 次（10 秒）
    Timer? retryTimer;

    Future<void> attemptLogin() async {
      if (!_isLoggingIn || !mounted) {
        retryTimer?.cancel();
        if (!_loginCompleter!.isCompleted) {
          _loginCompleter!.complete();
        }
        logger.w('登录尝试中止: isLoggingIn=$_isLoggingIn, mounted=$mounted');
        return;
      }

      retryCount++;
      logger.i('尝试登录（第 $retryCount 次），VPN 状态: $_vpnStatus');

      try {
        final provider = Provider.of<ProjectProvider>(context, listen: false);
        await provider.connect(connectionString);
        if (mounted && _isLoggingIn) {
          await _saveCredentials();
          Navigator.pushReplacementNamed(context, '/projects');
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('登录成功')));
          logger.i('登录成功');
        }
        retryTimer?.cancel();
        if (!_loginCompleter!.isCompleted) {
          _loginCompleter!.complete();
        }
      } catch (e) {
        logger.e('登录失败（第 $retryCount 次）: $e');
        if (retryCount >= maxRetries || _vpnStatus == 'CONNECTED') {
          retryTimer?.cancel();
          if (mounted && _isLoggingIn) {
            ScaffoldMessenger.of(
              context,
            ).showSnackBar(SnackBar(content: Text('登录失败: $e')));
          }
          if (!_loginCompleter!.isCompleted) {
            _loginCompleter!.complete();
          }
        }
      }
    }

    // 启动重试
    if (_isLoggingIn && _vpnStatus != 'CONNECTED' && retryCount < maxRetries) {
      retryTimer = Timer.periodic(const Duration(seconds: 1), (timer) async {
        if (!_isLoggingIn ||
            retryCount >= maxRetries ||
            _vpnStatus == 'CONNECTED') {
          timer.cancel();
          if (!_loginCompleter!.isCompleted) {
            _loginCompleter!.complete();
          }
          logger.i(
            '重试停止: isLoggingIn=$_isLoggingIn, retryCount=$retryCount, vpnStatus=$_vpnStatus',
          );
          return;
        }
        await attemptLogin();
      });
    }

    // 首次登录尝试
    await attemptLogin();

    await _loginCompleter!.future;

    if (mounted) {
      setState(() {
        _isLoading = false;
        _isLoggingIn = false;
      });
    }
  }

  void _navigateToVPNScreen(BuildContext context) {
    Navigator.pushNamed(context, '/vpn');
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false, // 禁用默认返回
      onPopInvokedWithResult: (didPop, result) async {
        if (didPop) return; // 已处理返回则跳过
        final now = DateTime.now();
        if (lastBackPressTime == null ||
            now.difference(lastBackPressTime!) > const Duration(seconds: 2)) {
          lastBackPressTime = now;
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(const SnackBar(content: Text('再按一次退出应用')));
          return;
        }
        try {
          await vpnService.disconnect();
        } catch (e) {
          logger.e('断开 VPN 失败: $e');
        }
        SystemNavigator.pop();
      },
      child: Scaffold(
        appBar: AppBar(title: const Text('登录')),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: _usernameController,
                focusNode: _usernameFocusNode,
                decoration: const InputDecoration(labelText: '用户名'),
                onSubmitted: (_) {
                  FocusScope.of(context).requestFocus(_passwordFocusNode);
                },
              ),
              TextField(
                controller: _passwordController,
                focusNode: _passwordFocusNode,
                decoration: const InputDecoration(labelText: '密码'),
                obscureText: true,
                onSubmitted: (_) => _login(context),
              ),
              Row(
                children: [
                  Checkbox(
                    value: _rememberPassword,
                    onChanged: (value) {
                      setState(() {
                        _rememberPassword = value ?? false;
                        if (!_rememberPassword) {
                          _autoLogin = false;
                        }
                      });
                    },
                  ),
                  const Text('记住密码'),
                  Checkbox(
                    value: _autoLogin,
                    onChanged: (value) {
                      setState(() {
                        _autoLogin = value ?? false;
                        if (_autoLogin) {
                          _rememberPassword = true;
                        }
                      });
                    },
                  ),
                  const Text('自动登录'),
                ],
              ),
              const SizedBox(height: 20),
              _isLoading
                  ? const CircularProgressIndicator()
                  : Column(
                      children: [
                        ElevatedButton(
                          onPressed: _isLoggingIn
                              ? null
                              : () => _login(context),
                          child: const Text('登录'),
                        ),
                        const SizedBox(height: 8),
                        ElevatedButton(
                          onPressed: _isLoggingIn
                              ? null
                              : () => _navigateToVPNScreen(context),
                          child: const Text('连接 VPN'),
                        ),
                        if (_isLoggingIn)
                          Padding(
                            padding: const EdgeInsets.only(top: 8.0),
                            child: ElevatedButton(
                              onPressed: _cancelLogin,
                              child: const Text('取消登录'),
                            ),
                          ),
                      ],
                    ),
            ],
          ),
        ),
      ),
    );
  }
}
